package com.baidumap.administrator.happystudy.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ab.dialog.loadingDialog.LoadingDialogUtil;
import com.ab.http.OnMessageResponse;
import com.ab.util.ToastUtil;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.adapter.BannarAdapter;
import com.baidumap.administrator.happystudy.api.Api;
import com.baidumap.administrator.happystudy.base.AppBaseActivity;
import com.baidumap.administrator.happystudy.base.Constant;
import com.baidumap.administrator.happystudy.broacast.AppBroadcastReceiver;
import com.baidumap.administrator.happystudy.model.AddCar;
import com.baidumap.administrator.happystudy.model.GoodsInfo2;
import com.baidumap.administrator.happystudy.model.M_QueRenDingDanGoods;
import com.baidumap.administrator.happystudy.model.ProductCollect;
import com.baidumap.administrator.happystudy.model.ProductDetail;
import com.baidumap.administrator.happystudy.model.StoreInfo;
import com.baidumap.administrator.happystudy.utils.GlideUtil;
import com.stx.xhb.xbanner.XBanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;


/**
 * author: C on 2017/3/21.
 * 商品详情
 */
public class GoodDetailActivity extends AppBaseActivity implements View.OnClickListener, OnMessageResponse, XBanner.XBannerAdapter {

    @Bind(R.id.tv_shop_name)
    TextView tvShopName;
    @Bind(R.id.tv_product_name)
    TextView tvProductName;
    @Bind(R.id.tv_product_price)
    TextView tvProductPrice;
    @Bind(R.id.tv_price_old)
    TextView tvPriceOld;
    @Bind(R.id.tv_sold_num)
    TextView tvSoldNum;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_xiang_qing)
    TextView tvXiangQing;
    @Bind(R.id.tv_totle_money)
    TextView tvTotalMoney;
    @Bind(R.id.ll_collect)
    LinearLayout ll_collect;


    private ViewPager viewPager;
    private TextView tvBuy;
    private TextView tvAdd;

    private String mProductId;

    @Bind(R.id.xbanner)
    XBanner mXBanner;

    private List<String> mImgesUrl;
    private List<String> mBannerDataList;

    @Override
    public int bindLayout() {
        return R.layout.activity_goods_detail;
    }

    @Override
    public void initView(View view) {
        super.initView(view);

        getBundleValue();
        viewPager = (ViewPager) view.findViewById(R.id.view_pager);
        tvBuy = (TextView) view.findViewById(R.id.tv_buy);
        tvAdd = (TextView) view.findViewById(R.id.tv_add);
        tvPriceOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        tvBuy.setOnClickListener(this);
        tvAdd.setOnClickListener(this);
        ll_collect.setOnClickListener(this);

        BannarAdapter viewpagerAdapter = new BannarAdapter(this);
        viewPager.setAdapter(viewpagerAdapter);

        mBannerDataList = new ArrayList<>();


    }

    /**
     * 获取bundleValue
     */
    private void getBundleValue() {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {

            mProductId = bundle.getString("product_id");
        }
    }

    @Override
    public void initData() {
        super.initData();

    }

    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);
        setHeaderBack();
        setHeaderTitle(R.string.product_detail);
        LoadingDialogUtil.showGifdialog(getSupportFragmentManager());
        Api.productDetail(this, mProductId);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.goback:
                finish();
                break;
            case R.id.tv_buy:

                Intent intent = new Intent();
                intent.setClass(this, QueRenDingDanActivity.class);
                intent.putExtra("M_QueRenDingDanGoods", m_queRenDingDanGoods);
                intent.putExtra("type", "lijigoumai");
                startActivityForResult(intent, 200);

//                Toast.makeText(this, "付款", Toast.LENGTH_SHORT).show();
                break;
            case R.id.tv_add:
                LoadingDialogUtil.showGifdialog(getSupportFragmentManager());
                Api.carAdd(this, sHelper.getString(Constant.TOKEN), sHelper.getString(Constant.UID), mProductId, "1");
//                startActivity(new Intent(this, ShoppingCarActivity.class));
                break;
            case R.id.ll_collect:
                LoadingDialogUtil.showGifdialog(getSupportFragmentManager());
                Api.productCollect(this, mProductId, sHelper.getString(Constant.UID), sHelper.getString(Constant.TOKEN));
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {

            Bundle bundle = data.getBundleExtra("data");


        }

    }


    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {

        if (url.equals(Constant.PRODUCT_DETAIL) && jo != null) {
            ProductDetail productDetail = new ProductDetail(jo.toString());

            if (productDetail != null) {


                if (productDetail.getCode().equals("200")) {


                    tvShopName.setText(productDetail.getData().getShop_name());
                    tvProductName.setText(productDetail.getData().getProduct_name());
                    tvProductPrice.setText("￥ " + productDetail.getData().getPrice_tuangou());
                    tvTotalMoney.setText("￥ " + productDetail.getData().getPrice_tuangou());
                    tvPriceOld.setText(productDetail.getData().getPrice());
                    tvSoldNum.setText("销量：" + productDetail.getData().getBuy_numbers() + "笔");
                    tvAddress.setText(productDetail.getData().getAddress());

                    String info = productDetail.getData().getInfo();
                    if (info != null) {
                        tvXiangQing.setText(Html.fromHtml(info));

                    }

                    mBannerDataList.add(productDetail.getData().getProduct_pic1());
                    mBannerDataList.add(productDetail.getData().getProduct_pic2());
                    mBannerDataList.add(productDetail.getData().getProduct_pic3());

                    initQueRenDingDanGoodsInfo(productDetail.getData());
                    initXBanner();

                } else {
                    ToastUtil.showMessage(this, productDetail.getMsg());
                }
            }


        }
        if (url.equals(Constant.CART_ADD) && jo != null) {

            AddCar addCar = new AddCar(jo.toString());

            if (addCar != null) {

                if (addCar.getCode().equals("200")) {
                    ToastUtil.showMessage(this, "添加购物车成功");
                    AppBroadcastReceiver.sendAppBroadcastReceiverMessage(this, Constant.INTENT_KEY.UPDATE_CART);
                } else {
                    ToastUtil.showMessage(this, "添加购物车失败");
                }
            }
        }
        if (url.equals(Constant.PRODUCT_COLLECT) && jo != null) {

            ProductCollect productCollect = new ProductCollect(jo.toString());

            if (productCollect != null) {

                if (productCollect.getCode().equals("200")) {
                    ToastUtil.showMessage(this, "收藏成功");
                } else {
                    ToastUtil.showMessage(this, "收藏失败");
                }
            }
        }
    }

    private List<StoreInfo> groups = new ArrayList<StoreInfo>();// 组元素数据列表
    private Map<String, List<GoodsInfo2>> children = new HashMap<String, List<GoodsInfo2>>();// 子元素数据列表
    M_QueRenDingDanGoods m_queRenDingDanGoods = new M_QueRenDingDanGoods();
    List<StoreInfo> selectedGoodsGroups = new ArrayList<>();
    List<List<GoodsInfo2>> toBeSelectedGoodsProducts = new ArrayList<>();
    List<GoodsInfo2> goodsProducts = new ArrayList<GoodsInfo2>();
    List<GoodsInfo2> products = new ArrayList<GoodsInfo2>();

    /**
     * 初始化确认订单商品信息
     *
     * @param dataBean
     */
    private void initQueRenDingDanGoodsInfo(ProductDetail.DataBean dataBean) {

        groups.add(new StoreInfo("0", dataBean.getShop_name(), dataBean.getShop_id()));

        products.add(new GoodsInfo2(dataBean.getProduct_id(), dataBean.getProduct_id(), dataBean.getProduct_name(), dataBean.getProduct_name(),
                Double.parseDouble(dataBean.getPrice_tuangou()), 1, "", "",
                dataBean.getProduct_pic1(), Double.parseDouble(dataBean.getPrice_tuangou()), "", "", "0", "0"));
        children.put(groups.get(0).getId(), products);// 将组元素的一个唯一值，这里取Id，作为子元素List的Key

        selectedGoodsGroups.add(groups.get(0));
        List<GoodsInfo2> childs = children.get(groups.get(0).getId());
        goodsProducts.add(childs.get(0));
        toBeSelectedGoodsProducts.add(goodsProducts);
        m_queRenDingDanGoods.setStoreInfoList(selectedGoodsGroups);
        m_queRenDingDanGoods.setGoodsInfo2List(toBeSelectedGoodsProducts);
    }

    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }

    /**
     * 初始化轮播图
     */

    private void initXBanner() {

        mImgesUrl = new ArrayList<>();
        for (int i = 0; i < mBannerDataList.size(); i++) {
            mImgesUrl.add(mBannerDataList.get(i));

        }
        //添加广告数据
        mXBanner.setData(mImgesUrl, null);//第二个参数为提示文字资源集合
        mXBanner.setmAdapter(this);
    }

    @Override
    public void loadBanner(XBanner banner, Object model, View view, int position) {

        GlideUtil.displayImgBanner(this, mImgesUrl.get(position), view);
    }

}
